package com.lyubia.shop.manager.controller;

import cn.hutool.core.util.StrUtil;
import com.lyubia.shop.api.pojo.Admin;
import com.lyubia.shop.api.service.CookieService;
import com.lyubia.shop.api.service.SSOService;
import com.lyubia.shop.common.result.BaseResult;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class LoginController {

    @Reference(version = "1.0")
    private SSOService ssoService;

    @Resource
    private CookieService cookieService;

    @GetMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    /**
     * 登录成功后
     *      1、将ticket放入Cookie中
     *      2、将用户信息存入Session中
     */
    @PostMapping("/login")
    @ResponseBody
    public BaseResult login(String username, String password, HttpServletRequest req, HttpServletResponse resp) {
        String ticket = ssoService.login(username, password);
        if (StrUtil.isNotEmpty(ticket)) {
            boolean b = cookieService.setCookie(ticket, req, resp);
            Admin admin = ssoService.checkTicket(ticket);
            req.getSession().setAttribute("user", admin);
            return b? BaseResult.success("登录成功!") : BaseResult.error("登录失败!");
        }
        return BaseResult.error("用户信息不存在或已过期");
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest req, HttpServletResponse resp) {
        String ticket = cookieService.getCookie(req);
        ssoService.logout(ticket);
        req.getSession().removeAttribute("user");
        cookieService.delCookie(req, resp);
        return "redirect:/toLogin";
    }

}
